package com.curd.websocketSQL;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

// WebSocket endpoint class
@ServerEndpoint("/websocket")
public class WebSocketEndpoint {

    @OnOpen
    public void onOpen(Session session) {
        // 当WebSocket连接打开时执行的逻辑
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 当接收到WebSocket消息时执行的逻辑
        saveMessageToDatabase(message);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        // 当WebSocket连接关闭时执行的逻辑
    }

    private void saveMessageToDatabase(String message) {
        // 使用JPA将消息保存到数据库中
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("持久性单元名称");
        EntityManager em = emf.createEntityManager();
        EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();

            WebSocketData data = new WebSocketData();
            data.setMessage();

            em.persist(data);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null && transaction.isActive()) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            em.close();
            emf.close();
        }
    }
}
